<template>
  <div class="content">
    <n-button type="info" @click="downloadCsv">导出CSV文件</n-button>

    <!-- 筛选框部分 -->
    <div class="filters" style="margin-top: 20px;">
      <n-select
        v-model:value="selectedRole"
        :options="roleOptions"
        placeholder="筛选角色"
        style="width: 200px; margin-right: 20px;" 
        clearable="true"
      />
      <n-select
        v-model:value="selectedStatus"
        :options="statusOptions"
        placeholder="筛选状态"
        style="width: 200px;"
        clearable="true"
      />
      <n-input placeholder="用户编号" style="width: 300px; margin-left: 20px" v-model:value="query"></n-input>

      <n-button type="info" @click="fetchUserList">查询</n-button>
    </div>

    <!-- 表格部分 -->
    <n-spin :show="loading" size="large">
      <n-data-table
        ref="tableRef" 
        :columns="columns"
        :data="userList"
        :pagination="paginationReactive"
        :bordered="true"
        :scroll-x="true"
        striped
        style="margin-top: 20px; max-height: 700px;" 
        :get-csv-cell="getCsvCell"
        :get-csv-header="getCsvHeader"
      />
    </n-spin>
  </div>
</template>

<script setup>
import { h, onMounted, reactive, ref, computed } from 'vue';
import { NButton, NDataTable, NIcon, NIconWrapper, NTag, NSpin, NSelect,NInput } from 'naive-ui';
import axiosInstance from '@/utils/axios';
import { Check, X,Lock } from '@vicons/tabler';

const tableRef = ref(null);

// 选择的筛选条件
const selectedRole = ref(null);
const selectedStatus = ref(null);
const query = ref(null);

// 角色和状态选项
const roleOptions = computed(() => roleList.map(role => ({
  label: role.role_name,
  value: role.role_id,
})));

const statusOptions = [
  { label: '可用', value: 1 },
  { label: '禁用', value: 0 },
];

// 表格列定义
const columns = createColumns({
  async play(row) {
    loading.value = true;
    try {
      const response = await axiosInstance.get('/api/update_user_status', {
        params: { user_id: row.user_id },
      });

      if (response.data.success) {
        row.user_status = row.user_status === 1 ? 0 : 1;
      }
    } catch (error) {
      console.error('请求失败', error);
    } finally {
      loading.value = false;
    }
  },

  async changeRole(row, newRole) {
    loading.value = true;
    try {
      const response = await axiosInstance.get('/api/update_user_role', {
        params: { user_id: row.user_id, role_id: newRole },
      });
      console.log(response.data)
      if (response.data.success) {
        const updatedRole = roleList.find(role => role.role_id === newRole);
        if (updatedRole) {
          row.role_name = updatedRole.role_name;
        }
      }
    } catch (error) {
      console.error('请求失败', error);
    } finally {
      loading.value = false;
    }
  }
});

function createColumns({ play, changeRole }) {
  return [
    { title: '创建时间', key: 'create_time' },
    { title: '用户编号', key: 'user_id', width: 100, ellipsis: { tooltip: true } },
    {
      title: '用户角色',
      key: 'role_name',
      render(row) {
        let roleColor = 'default';
        if (row.role_name === '管理员') roleColor = 'error';
        else if (row.role_name === '用户') roleColor = 'success';
        else if (row.role_name === '客服') roleColor = 'warning';
        return h(NTag, { type: roleColor }, row.role_name);
      }
    },
    {
      title: '用户状态',
      key: 'user_status',
      render(row) {
        return h(
            NIconWrapper,
            {
              color: row.user_status === 1 ? 'green' : (row.user_status === 2 ? 'blue' : 'red'),
            },
            {
              default: () => h(NIcon, {
                component: row.user_status === 1 ? Check : (row.user_status === 2 ? Lock : X)
              })
            }
          );
      }
    },
    {
      title: '角色更换',
      key: 'role',
      render(row) {
        return h(
          NSelect,
          {
            style: { marginLeft: '-20px' },
            options: roleList.map(role => ({
              label: role.role_name,
              value: role.role_id,
            })),
            onChange: (newRole) => changeRole(row, newRole),
            value: row.role_name,
            size: 'small',
          }
        );
      }
    },
    {
      title: '操作',
      key: 'actions',
      render(row) {
        return h('div', [
          h(
            NButton,
            {
              type: row.user_status === 1 ? 'error' : 'success',
              strong: true,
              size: 'small',
              onClick: () => play(row),
            },
            { default: () => (row.user_status === 1 ? '禁用' : '启用') }
          )
        ]);
      },
    },
  ];
}

const userList = reactive([]);


const maxpage = ref(0);
const loading = ref(false);
const roleList = reactive([]);

const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [3, 5, 10],
  onChange(page) {
    loading.value = true;
    if (page > paginationReactive.page && page > maxpage.value) {
      paginationReactive.page = page;
      fetchUserList(page, paginationReactive.pageSize);
    } else {
      paginationReactive.page = page;
      loading.value = false;
    }
  },
  onUpdatePageSize(pageSize) {
    paginationReactive.pageSize = pageSize;
    paginationReactive.page = 1;
  },
});

const fetchUserList = async () => {
  try {
    loading.value = true;
    const data = {
      page: 1,
      page_size: 500
    };

    // 如果有选择角色，加入 user_role_id 参数
    if (selectedRole.value !== null) {
      data.user_role_id = selectedRole.value;
    }

    // 如果有选择用户状态，加入 user_status 参数
    if (selectedStatus.value !== null) {
      data.user_status = selectedStatus.value;
    }

    // 如果有输入用户编号，加入 user_id 参数
    if (query.value) {
      data.user_id = query.value;
    }

    // 将 data 作为请求体发送
    const response = await axiosInstance.post('/api/userlist', data);

    if (response.data.success) {
      userList.length = 0;
      userList.push(...response.data.data);
      maxpage.value = Math.ceil(response.data.total / paginationReactive.pageSize);
    } else {
      console.error('没有用户数据');
    }
  } catch (error) {
    console.error('请求失败', error);
  } finally {
    loading.value = false;
  }
};

const fetchRoleList = async (page = 1, pageSize = 10) => {
  try {
    const response = await axiosInstance.post('/api/get_role_list', { page, page_size: pageSize });
    if (response.data.success) {
      roleList.push(...response.data.data);
    } else {
      console.error('没有角色数据');
    }
  } catch (error) {
    console.error('请求失败', error);
  }
};

onMounted(() => {
  fetchUserList();
  fetchRoleList();
});

const downloadCsv = () => {
  const columnsForCsv = columns.map(col => ({
    title: col.title,
    key: col.key,
  }));

  const dataForCsv = userList.map(user => {
    const row = {};
    columnsForCsv.forEach(col => {
      if (col.key === 'user_status') {
        row[col.key] = user[col.key] === 1 ? '可用' : '禁用';
      } else {
        row[col.key] = user[col.key];
      }
    });
    return row;
  });

  tableRef.value?.downloadCsv({
    fileName: 'user-list',
    data: dataForCsv,
    columns: columnsForCsv,
  });
};


</script>

<style scoped>
.content {
  margin-left: 60px;
  margin-top: 20px;
  height: 1000px;
  width: 1130px;
}

.filters {
  display: flex;          
  gap: 20px;             
  margin-bottom: 20px;    
}
</style>
